﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CRM_Project
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                pudate.TodaysDate = DateTime.Now;
                pudate.SelectedDate = DateTime.Now;
                dodate.SelectedDate = DateTime.Now.AddDays(3);

                Button1_Click(null, null);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            crmengine crme = new crmengine();
            GridView1.DataSource = from Car c in crme.Cars
                                   where (from Reservation r in c.Reservations
                                          where r.StartTime <= dodate.SelectedDate && r.EndTime >= pudate.SelectedDate
                                          select r).Count() == 0
                                   select new {ModelName = c.Model.Name, c.Mileage, c.Color, LotName = c.Lot.Name, ID};
            DataBind();
        }

        protected void ReserveButton(object sender, EventArgs e)
        {
            crmengine crme = new crmengine();
            
            Reservation nr = new Reservation();
            nr.CustomerName = NameTextBox.Text;
            nr.StartTime = pudate.SelectedDate;
            nr.EndTime = dodate.SelectedDate;
            nr.CreditCardNumber = 0;
            
            var Cars = from Car c in crme.Cars
                       where (from Reservation r in c.Reservations
                              where r.StartTime <= dodate.SelectedDate && r.EndTime >= pudate.SelectedDate
                              select r).Count() == 0
                       select c;

            GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
            nr.Car = Cars.ToArray()[row.RowIndex];
            nr.StartLot = nr.Car.Lot;
            nr.EndLot = nr.Car.Lot;

            crme.Reservations.InsertOnSubmit(nr);
            crme.SubmitChanges();

            Button1_Click(null, null);
        }
    }
}
